package com.bgt.action;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.nobject.common.fan.datagen.RandomGen;

import com.bgt.model.MUser;
import com.bgt.service.MUserService;
import com.bgt.service.impl.MUserServiceImpl;
import com.bgt.utils.HttpUtils;
import com.mysql.jdbc.Constants;
import com.opensymphony.xwork2.ActionContext;

import net.sf.json.JSONObject;



public class MUserAction {
	private MUserService userService=new MUserServiceImpl();
	private Map<String,Object> dataMap;  
	private MUser usertem;
	private JSONObject resultObj = new JSONObject();  
	public String addUser(){
		dataMap = new HashMap<String, Object>();  
		try{
		MUser user=new MUser();
		user.setId(UUID.randomUUID().toString().replace("-",""));
		user.setUserName(usertem.getUserName());
		user.setPassWord(usertem.getPassWord());
		System.out.println(user);
		userService.addUser(user);
		 dataMap.put("success", true);
		 dataMap.put("msg", "用户添加成功");
		}catch(Exception e){
			e.printStackTrace();
			dataMap.put("success", false);
			dataMap.put("msg", "用户添加失败");
			
		}
		return "json";
	}
	public String login(){
		HttpServletRequest request=HttpUtils.getRequest();
		HttpSession session=request.getSession();
		try{
		/*String name=request.getParameter("name");
		String pwd=request.getParameter("pwd");*/
			String code=request.getParameter("code");
			String codein=(String) request.getSession().getAttribute("safecode");
			System.out.println(codein+"-----");
		dataMap = new HashMap<String, Object>();  
		/*if(!code.equals(codein)){
			dataMap.put("success", false);
			dataMap.put("msg", "验证码错误");
			return "json";
		}*/
		MUser user=userService.getUserByNameAndPwd(usertem.getUserName(), usertem.getPassWord());
		if(user==null){
			dataMap.put("success", false);
			dataMap.put("msg", "用户不存在");
		}else{
		session.setAttribute("currentUser", user);
		dataMap.put("success", true);
		dataMap.put("msg", "用户登录成功");
		}
		}catch(Exception e){
			e.printStackTrace();
			dataMap.put("success", false);
			dataMap.put("msg", "用户登录失败"+e.getMessage());
			return "json";
		}
		return "json";
	}
	public String loginout(){
		HttpServletRequest request=HttpUtils.getRequest();
		HttpSession session=request.getSession();
		dataMap = new HashMap<String, Object>();  
		session.setAttribute("currentUser", null);
		dataMap.put("success", true);
		dataMap.put("msg", "用户登出成功");
	return "json1";
}
	public String initAddUser(){
		return "initAddUser";
	}
	public String initAddUser2(){
		return "initAddUser2";
	}
	public String initUsers(){
		return "initUsers";
	}
	public String UserList(){
		HttpServletRequest request=HttpUtils.getRequest();
		String name=request.getParameter("name");
		String sort=request.getParameter("sort");
		String order=request.getParameter("order");
		String startsize=request.getParameter("page");
		String pagesize=request.getParameter("rows");
		Integer start=Integer.valueOf(startsize)>1?(Integer.valueOf(startsize)-1)*Integer.valueOf(pagesize):0;
		Map<String,String> params=new LinkedHashMap<String, String>();
		params.put("startsize",String.valueOf(start));
		params.put("pagesize","10");
		params.put("sort",sort);
		params.put("order",order);
		params.put("username", name);
		List<MUser> listtem=userService.getUsersPage2(params);
		JSONObject jj = JSONObject.fromObject(listtem.get(0));
		dataMap = new HashMap<String, Object>();  
//		resultObj = new JSONObject();
//		JSONArray ja = JSONArray.fromObject(listtem);
//		resultObj.put("total", 8);
		dataMap.put("total", userService.countUsersPage2(params));
		dataMap.put("rows", listtem);
//		resultObj.put("rows", listtem);
//		Gson g=new Gson();
		//String s=g.toJson(listtem);
		//System.out.println(s);
//		String s2=g.toJson(dataMap);
//		System.out.println(s2);
		return "userlist";
	}
	public Map<String, Object> getDataMap() {
		return dataMap;
	}
	public void setDataMap(Map<String, Object> dataMap) {
		this.dataMap = dataMap;
	}
	public MUser getUsertem() {
		return usertem;
	}
	public void setUsertem(MUser usertem) {
		this.usertem = usertem;
	}
	public JSONObject getResultObj() {
		return resultObj;
	}
	public void setResultObj(JSONObject resultObj) {
		this.resultObj = resultObj;
	}
	public String genradomCodeImage() throws Exception{
		HttpServletRequest req= HttpUtils.getRequest();
		HttpServletResponse resp= HttpUtils.getResponse();
		
		// 设置响应头 Content-type类型
		resp.setContentType("image/jpeg");
		// 以下三句是用于设置页面不缓存
		resp.setHeader("Pragma", "No-cache");
		resp.setHeader("Cache-Control", "No-cache");
		resp.setDateHeader("Expires", 0);

		OutputStream os = resp.getOutputStream();
		int width = 103, height = 30;
		// 建立指定宽、高和BufferedImage对象
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);

		Graphics g = image.getGraphics(); // 该画笔画在image上
		Color c = g.getColor(); // 保存当前画笔的颜色，用完画笔后要回复现场
		g.fillRect(0, 0, width, height);
		//defghjkmnpqrstuvwxyz
		char[] ch = "abcdefghjkmnpqrstuvwxyz23456789".toCharArray(); // 随即产生的字符串
																		// 不包括 i
																		// l(小写L)
																		// o（小写O）
																		// 1（数字1）0(数字0)
		int length = ch.length; // 随即字符串的长度
		String sRand = ""; // 保存随即产生的字符串
		Random random = new Random();
		// 设置随机颜色
		g.setColor(new Color(random.nextInt(255), random.nextInt(255),
				random.nextInt(255)));
		for (int i = 0; i < 4; i++) {
			// 设置字体
			g.setFont(getFont());
			// 随即生成0-9的数字
			String rand = new Character(ch[random.nextInt(length)]).toString();
			sRand += rand;
			
			//黑色
//			g.setColor(new Color(0, 0,
//					0));
			g.drawString(rand, 20 * i + 6, 25);
		}
		// 产生随即干扰点
		for (int i = 0; i < 20; i++) {
			int x1 = random.nextInt(width);
			int y1 = random.nextInt(height);
			g.drawOval(x1, y1, 2, 2);
		}
		g.setColor(c); // 将画笔的颜色再设置回去
		g.dispose();

		// 将验证码记录到session
		req.getSession().setAttribute("safecode", sRand);
		System.out.println(req.getSession().getAttribute("safecode"));
		// 输出图像到页面
		ImageIO.write(twistImage(image), "JPEG", os);
		return null;
}

/**
 * 
 * @Description:正弦曲线Wave扭曲图片
 * @since 1.0.0
 * @Date:2012-3-1 下午12:49:47
 * @return BufferedImage
 */
private BufferedImage twistImage(BufferedImage buffImg) {
    double dMultValue = RandomGen.random.nextInt(10) + 3;// 波形的幅度倍数，越大扭曲的程序越高，一般为3
    double dPhase = RandomGen.random.nextInt(6);// 波形的起始相位，取值区间（0-2＊PI）

    BufferedImage destBi = new BufferedImage(buffImg.getWidth(),
            buffImg.getHeight(), BufferedImage.TYPE_INT_RGB);

    for (int i = 0; i < destBi.getWidth(); i++) {
        for (int j = 0; j < destBi.getHeight(); j++) {
            int nOldX = getXPosition4Twist(dPhase, dMultValue,
                    destBi.getHeight(), i, j);
            int nOldY = j;
            if (nOldX >= 0 && nOldX < destBi.getWidth() && nOldY >= 0
                    && nOldY < destBi.getHeight()) {
                destBi.setRGB(nOldX, nOldY, buffImg.getRGB(i, j));
            }
        }
    }
    return destBi;
}

/**
 * 
 * @Description:获取扭曲后的x轴位置
 * @since 1.0.0
 * @Date:2012-3-1 下午3:17:53
 * @param dPhase
 * @param dMultValue
 * @param height
 * @param xPosition
 * @param yPosition
 * @return int
 */
private int getXPosition4Twist(double dPhase, double dMultValue,
        int height, int xPosition, int yPosition) {
    double PI = 3.1415926535897932384626433832799; // 此值越大，扭曲程度越大
    double dx = (double) (PI * yPosition) / height + dPhase;
    double dy = Math.sin(dx);
    return xPosition + (int) (dy * dMultValue);
}

Font font[] = new Font[]{
	new Font("Georgia"		, Font.BOLD, 32),
	new Font("Verdana"		, Font.BOLD, 32),
	new Font("Arial"		, Font.BOLD, 32),
	new Font("Tahoma"		, Font.PLAIN, 32),
	new Font("Time News Roman", Font.BOLD, 32),
	new Font("Courier New"	, Font.BOLD, 32),
	new Font("Arial Black"	, Font.BOLD, 32),
	new Font("Quantzite"	, Font.BOLD, 32)
	
};

/** 
 * getFont
 * @return
 */
private Font getFont() {
	Random random = new Random();
	return font[random.nextInt(font.length)];
}
}
